using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
    public class StudentGradeRepository : Repository<StudentGrade>, IStudentGradeRepository
    {
        protected override Expression<Func<StudentGrade, int>> PrimaryKeyExpression => r => r.Id;
        private readonly IStudentRepository _studentRepository;

        public StudentGradeRepository(ApiDBContent context,
        IStudentRepository studentRepository) : base(context)
        {
            _studentRepository = studentRepository;
        }

        protected override void UpdateEntitiesBeforeCreate(IEnumerable<StudentGrade> entities, ApiDBContent context)
        {
           foreach (var entity in entities)
           {
                entity.UserId = AuthInfo.UserId;
                if (AuthInfo.UserEntity.SchoolId.HasValue)
                {
                    entity.SchoolId = AuthInfo.UserEntity.SchoolId.Value;
                }
            }
        }

        protected override IQueryable<StudentGrade> FilterByAuthInfo(IQueryable<StudentGrade> queryable, ApiDBContent context)
        {
            if (AuthInfo.IsAdmin)
            {
                return queryable;
            }

            queryable = queryable.Where(r => r.SchoolId == AuthInfo.UserEntity.SchoolId && r.UserId == AuthInfo.UserId);
            return queryable;
        }

        protected override void UpdateEntitiesAfterDelete(IEnumerable<StudentGrade> entities, ApiDBContent context)
        {
            DeleteStudent(entities);
        }

        private void DeleteStudent(IEnumerable<StudentGrade> entities)
        {
            var gradeIds = entities.Select(r => r.Id).ToList();
            var students = _studentRepository.FindAll().Where(r => gradeIds.Contains(r.ClassId)).ToList();
            students.ForEach(student =>
            {
                student.Deleted = true;
            });

            _studentRepository.UpdateRangeByDBContext(students);
        }
    }
}